package com.aabte.lock.jedis.v3;

import org.apache.commons.lang3.StringUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

/**
 * 抢购商品的业务逻辑
 */
public class ProductRedisTransactionProcess implements IRedisTransactionProcess {

    private int productNumber;

    @Override
    public boolean invokeBeforeProcess(Jedis jedis, String lockKey) {
        String productNumStr = jedis.get(lockKey);
        if (StringUtils.isNumeric(productNumStr)) {
            int productNum = Integer.parseInt(productNumStr);
            if (productNum > 0) {
                productNumber = productNum;
                return true;
            }
        }
        System.out.println(String.format("%s 商品已被抢空！", Thread.currentThread()));
        return false;
    }

    @Override
    public void invokeProcess(Transaction transaction, String lockKey) {
        // 数据库操作
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(String.format("%s 正在提交...", Thread.currentThread().getName()));
        transaction.set(lockKey, String.valueOf(productNumber - 1));
    }

    @Override
    public void rollback(Jedis jedis, String lockKey) {
        System.out.println(String.format("%s 抢购失败，正在重试中...", Thread.currentThread().getName()));
    }

    @Override
    public void invokePostProcess(Jedis jedis, String lockKey) {
        System.out.println(String.format("%s 商品抢购成功！", Thread.currentThread().getName()));
    }
}
